from django.shortcuts import render, HttpResponse
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from app01.utils.form import TaskModelForm
import json
from app01 import models
from app01.utils.pageination import Pagination


def task_list(request):  # 获取任务列表
    queryset = models.Task.objects.all().order_by('-id')
    page_object = Pagination(request, queryset)
    form = TaskModelForm()
    context = {
        'queryset': page_object.page_queryset,
        'page_str': page_object.html(),
        'form': form
    }
    return render(request, 'task_list.html', context)


@csrf_exempt
def task_add(request):
    form = TaskModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        data_dict = {'status': True}
        # return JsonResponse(data_dict)
        return HttpResponse(json.dumps(data_dict))

    data_dict = {'status': False, 'error': form.errors}
    return HttpResponse(json.dumps(data_dict, ensure_ascii=False))
